package com.hy.utils.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(value = "/view/*", filterName = "HTMLFilter")
public class HTMLFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        HTMLHttpServletRequest hrequest = new HTMLHttpServletRequest(request);

        chain.doFilter(hrequest, response);
    }

    @Override
    public void destroy() {

    }

    private class HTMLHttpServletRequest extends HttpServletRequestWrapper{

        public HTMLHttpServletRequest(HttpServletRequest request) {
            super(request);
        }

        public String getParameter(String name){
           /* System.out.println("pa666");*/
            String value =  super.getParameter(name);

            if(value == null)
                return null;

            value = htmlFilter(value);

            return value;
        }

        private String htmlFilter(String value) {
            if(value == null)
                return null;

            char[] chars = value.toCharArray();

            StringBuffer sb = new StringBuffer();

            for (int i = 0,len = chars.length; i < len; i++) {
                switch (chars[i]){
                    case '>':
                        sb.append("&gt;");
                        break;
                    case '<':
                        sb.append("&lt;");
                        break;
                    case '&':
                        sb.append("&amp;");
                        break;
                    case '"':
                        sb.append("&quot;");
                        break;
                    default:
                        sb.append(chars[i]);
                        break;
                }
            }

            return null;
        }
    }
}
